var modifyOrAddFlag;
//初始化数据
$(document).ready(function(){
		$('#winEdit').window('close');


		
		$(".button_con a" ).removeClass("l-btn-plain");
		$('#JScompany').combobox({
			url: BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'orgName',
		    editable: false,
		    method:'get',
		    loadFilter:function(data){
		    	var allCheck = {'id':'','orgName':'全部'};
		    	data.content.unshift(allCheck);
		    	return data.content;
		    },
		    onLoadSuccess:function(){
		    	$('#JScompany').combobox('setValue','');
		    }
		});
		
		/*$('#comboxCompanyName').combobox({
			editable: false,
			url: BASE_URL_COMPANY_SEARCH + '/findByExample' + '?v=' + Math.random(),
			valueField: 'id',
		    textField: 'orgName',
		    method:'get',
		    loadFilter:function(data){
		    	return data.content;
		    }
		    
		});*/
		$("#datagrid").datagrid({
			url : BASE_URL_COMPANY_SEARCH + '/findByExamples' + '?v=' + Math.random(),
			method:'get',
			autoRowHeight:true,//自动行高
			singleSelect: true,//单选
			striped:true,
			nowrap:false,
			pagination:true,
			pageSize:20,
			pageList:[10,20,50,100],
			columns:[[
						{field:'',width:10,checkbox:true},
						{field:'orgNameFor',title:'所属公司',width:100},
						{field:'orgName',title:'部门名称',width:100},
			      ]],
			loadFilter:function(data){
				return {
					total: data.totalElements,
					rows: data.content
				};
			},
			onBeforeLoad:function(param){
				param.page -= 1;
				param.size = param.rows;
				delete param.rows;
				
				param.sort = 'createTime,desc';
				var id = $('#JScompany').combobox('getValue');
				if(id !=""){
					param.id = id;
				}
				
				var name = $('#JSdepartment').val();
				if(name !=""){
					param.name = name;
				}
				
			}
		});
		
		$("#datagrid").datagrid('getPager').pagination({   
		    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 

	});
	function onAdd(){
		modifyOrAddFlag = true;
		$('#addForm')[0].reset();
		var data = $('#comboxCompanyName').combobox('getData');
		$("#comboxCompanyName").combobox('setValue',data[0].id);
		$("#comboxCompanyName").siblings(".textbox").children(".textbox-text").val($("#comboxCompanyName").combobox('getText'));
		
		$("#winEdit").window('setTitle','公司部门管理-新增');
		$('#winEdit').window('open');
	}
	//新增和修改保存
	function onSave(){
		if($("#addForm").form("validate")){
			$("#instance_save").linkbutton("disable");
			$("#instance_save .l-btn-text").text("提交中...");
			
			var orgName = $("#comboxDepartment").val();
			var parent = $('#comboxCompanyName').combobox('getValue');
			var level ='2';
			departmentInfo = {
					orgName:orgName,
					level:'2',
					parent:BASE_URL_COMPANY+'/'+$('#comboxCompanyName').combobox('getValue')
					
			};
			var checkParam = {name:orgName,parent:parent,level:level};
			if(!modifyOrAddFlag){
				var row = $('#datagrid').datagrid('getSelected');
				checkParam.originalId = row.id;
				alert(row.id);
	 	 		if(row.orgName == checkParam.name && row.orgNameFor==checkParam.parent) // 未修改领域部门的名字，则可以直接修改
				{
	 	 			alert("success");
	 	 			modifydepartment(departmentInfo);
				}
				else
				{
					$.ajax({
			    		type: "get",
			    		url: BASE_URL_COMPANY_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
			    		data: checkParam,
			    		contentType: "application/json",
			    		success: function(result) {
			    			if(result.isCanSave == true)
		    				{
			    				modifydepartment(departmentInfo);
		    				}
		    				else 
	    					{
		    					if (result.errorCode == "DUPLICATE") 
								{
			    					$("#instance_save").linkbutton("enable");
			    					$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败，部门已存在或者和公司重名！</p>","error");
								}
								else
								{
									$("#instance_save").linkbutton("enable");
									$("#instance_save .l-btn-text").text("保存");
									$.messager.alert('错误',"<p>修改失败！</p>","error");
								}
	    					}
			    		},
						error: function() {
							$("#instance_save").linkbutton("enable");
							$("#instance_save .l-btn-text").text("保存");
							$.messager.alert('错误','<p>服务异常，修改部门信息失败，请稍后重试或联系管理员!</p>', 'error');
						}
			    	});
				}				
			}else{
				$.ajax({
		    		type: "get",
		    		url: BASE_URL_COMPANY_SEARCH + '/checkIsCanSave' + '?v=' + Math.random(),
		    		data: checkParam,
		    		contentType: "application/json",
		    		success: function(result) {
		    			if(result.isCanSave == true)
	    				{
		    				addDepartment(departmentInfo)
	    				}
	    				else 
    					{
	    					if (result.errorCode == "DUPLICATE") 
							{
		    					$("#instance_save").linkbutton("enable");
		    					$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败，部门名称已存在或者和公司名称重名！</p>","error");
							}
							else
							{
								$("#instance_save").linkbutton("enable");
								$("#instance_save .l-btn-text").text("保存");
								$.messager.alert('错误',"<p>新增失败！</p>","error");
							}
    					}
		    		},
					error: function() {
						$("#instance_save").linkbutton("enable");
						$("#instance_save .l-btn-text").text("保存");
						$.messager.alert('错误','<p>服务异常，新增部门信息失败，请稍后重试或联系管理员!</p>', 'error');
					}
		    	});
			}
		}
	}
	
	function addDepartment(departmentInfo) {
		if(!departmentInfo)
		{
			var orgName = $("#comboxDepartment").val();
			var parent = $("#comboxCompany").combobox('getValue');
			departmentInfo = {
					orgName:orgName,
					parent:BASE_URL_COMPANY+'/'+ $('#comboxCompanyName').combobox('getValue'),
					level:'2'
			};
		}
		var jsonStr = JSON.stringify(departmentInfo);
		$.ajax({
			url: BASE_URL_COMPANY + '?v=' + Math.random(),
			type:'post',
			contentType:"application/json",
			data: jsonStr,
			timeout:30000,
			success:function(){
				$.messager.alert('提示',"<p>新增成功!</p>","info");
				$('#winEdit').window('close');
				$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExamples' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，新增部门失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
		});
	}
	
	function modifydepartment(departmentInfo) {
		var row = $('#datagrid').datagrid('getSelected');
		if(!departmentInfo)
		{
			var orgName = $("#comboxDepartment").val();
			var parent = $("#comboxCompany").combobox('getValue');
			departmentInfo = {
					orgName:orgName,
					parent:BASE_URL_COMPANY+'/'+ $('#comboxCompanyName').combobox('getValue'),
					level:'2'
			};
		}
		var jsonStr = JSON.stringify(departmentInfo);
		$.ajax({
			url:BASE_URL_COMPANY_CRUD + '/' + row.id  + '?v=' + Math.random(),
			dataType:'json',
			type:'put',
			contentType:"application/json",
			data: jsonStr,
			success:function(){
				$.messager.alert('提示',"<p>修改成功!</p>","info");
				$('#winEdit').window('close');
				$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExamples' + '?v=' + Math.random());
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			},
			error:function(xhr,s,err){
				$.messager.alert("错误","<p>服务异常，修改部门信息失败，请重新登录或稍后再试！</p>","error");	
				$("#instance_save").linkbutton("enable");
				$("#instance_save .l-btn-text").text("保存");
			}
			
			
		});
	}
	
	//修改提示
	function onUpdate(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要修改的记录</p>","warning");
		}else{
			modifyOrAddFlag = false;
			$("#comboxCompanyName").combobox('setValue',row.orgNameForid);
			$("#comboxCompanyName").siblings(".textbox").children(".textbox-text").val($("#comboxCompanyName").combobox('getText'));
			$("#comboxDepartment").val(row.orgName);
			$("#winEdit").window('setTitle','部门管理-修改');
			$('#winEdit').window('open');
		}
	}
	//删除
	function onDel(){
		var row = $('#datagrid').datagrid('getSelected');
		if(row == null){
			$.messager.alert('警告',"<p>请选中要删除的记录</p>","warning");
			return;
		}
					$.messager.confirm('温馨提示','<p>你真的要删除么?</p>',function(result){
						if (result){
					 		$.ajax({
								url:BASE_URL_COMPANY_CRUD + '/' + row.id + '?v=' + Math.random(),
								dataType:'json',
								type:'delete',
								async:false,
								contentType:"application/json",
								timeout:30000,
								success:function(){
									$.messager.alert('提示',"<p>删除成功!</p>","info");
									$("#datagrid").datagrid("reload", BASE_URL_COMPANY_SEARCH + '/findByExamples' + '?v=' + Math.random());
								},
								error:function(xhr,s,err){
									$.messager.alert("错误","<p>服务异常，删除部门失败，请重新登录或稍后再试！</p>","error");	
								}
					 		});
						}
					});
	}
	
	function onCancleEdit(){
		$('#winEdit').window('close');
	}
	
	function onSearch(){
		$('#datagrid').datagrid('load');
	}

 	
 	